package ic

import (
	"bytes"
	"fmt"
	"image"
	"image/gif"
)

type GIFConverter struct{}

func (g *GIFConverter) SupportedFormat() string {
	return "GIF"
}

func (g *GIFConverter) FileExtension() string {
	return ".gif"
}

func (g *GIFConverter) MimeType() string {
	return "image/gif"
}

func (g *GIFConverter) Encode(img image.Image, options ...Options) ([]byte, error) {
	var buf bytes.Buffer

	// 合并选项
	opts := MergeOptions(options...)

	// GIF使用颜色数量配置
	numColors := opts.NumColors
	if numColors <= 0 || numColors > 256 {
		numColors = 256
	}

	gifOptions := &gif.Options{
		NumColors: numColors,
	}

	if err := gif.Encode(&buf, img, gifOptions); err != nil {
		return nil, fmt.Errorf("GIF编码失败: %v", err)
	}

	return buf.Bytes(), nil
}

func (g *GIFConverter) Decode(data []byte) (image.Image, error) {
	return gif.Decode(bytes.NewReader(data))
}
